package net.wicp.tams.common.apiext.fastjson;

import java.io.IOException;
import java.lang.reflect.Type;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;

/***
 * 把对象转成js的json对象
 * 
 * @author 偏锋书生
 *
 */
public class SerializerJsonByJs implements ObjectSerializer {

	@Override
	public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features)
			throws IOException {
		SerializeWriter out = serializer.getWriter();
		if (object == null) {
			serializer.getWriter().writeNull();
			return;
		}
		Object tempobj = JSONObject.toJSON(object);
		if (!(tempobj instanceof JSONObject)) {
			throw new IllegalArgumentException("只支持普通对象");
		}
		JSONObject jsonObject = (JSONObject) tempobj;
		String retstr = jsonObject.toJSONString();
		for (String key : jsonObject.keySet()) {
			String value = jsonObject.getString(key);
			retstr = retstr.replace(String.format("\"%s\":", key), key + ":");
			retstr = retstr.replace(String.format(":\"%s\",", value), String.format(":'%s',", value));
		}
		out.write(retstr);
	}

}
